from functools import wraps

from comtypes.tools.codegenerator.codegenerator import logger
from huey import RedisHuey,crontab
from src.utils.logger import get_logger
import config
from typing import Dict, Callable
logger = get_logger("caput")

# 创建 Huey 实例
huey = RedisHuey(**config.HUEY_CONFIG)
logger.info("Huey队列实例创建成功")

# 存储已注册的任务
registered_tasks: Dict[str, Callable] = {}

def register_task(func):
    """任务注册装饰器"""
    @huey.task()
    # @huey.periodic_task(crontab(minute='*/1'))
    def wrapped(*args, **kwargs):
        try:
            logger.info(f"执行任务: {func.__name__}")
            result = func(*args, **kwargs)
            logger.info(f"任务完成: {func.__name__}")
            return result
        except Exception as e:
            logger.error(f"任务失败: {func.__name__}, 错误: {str(e)}")
            raise
    
    # 记录已注册的任务
    registered_tasks[func.__name__] = wrapped
    # logger.info(f"任务已注册: {func.__name__}")
    return wrapped

def print_registered_tasks():
    """打印所有已注册的任务"""
    logger.info("已注册的任务列表:")
    if not registered_tasks:
        logger.info("暂无注册任务")
        return
        
    for task_name, task_func in registered_tasks.items():
        logger.info(f"- {task_name}")

# convinience crontab definitions
def cron_daily(hour='17', minute='0'):
    return crontab(hour=hour, minute=minute)

def app_context(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        # FastAPI没有Flask的app_context，但你可以在这里初始化一些资源
        return f(*args, **kwargs)
    return wrapper